<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="资源类型" prop="resourceType">
        <el-select v-model="queryParams.resourceType" class="m-2" placeholder="Select" size="large">
          <el-option label="应用" :value="1"/>
          <el-option label="页面" :value="2"/>
          <el-option label="元素" :value="4"/>
        </el-select>
      </el-form-item>
      <el-form-item label="资源名称" prop="title">
        <el-input v-model="queryParams.title" placeholder="请输入资源名称" clearable style="width: 240px" @keyup.enter="handleQuery"/>
      </el-form-item>
      <el-form-item label="权限标识" prop="permission">
        <el-input v-model="queryParams.permission" placeholder="请输入权限标识" clearable style="width: 240px" @keyup.enter="handleQuery"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="20" class="mb8">
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>
    <el-table ref="tableDom" border stripe v-loading="loading" :data="resourceList" row-key="id" lazy :load="loadNextNode"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }" @expand-change="treeTableExpandChange">
      <el-table-column label="资源名称" align="left" header-align="center" prop="title" v-if="columns[0].visible"
                       :show-overflow-tooltip="true"/>
      <el-table-column label="资源类型" align="left" header-align="center" prop="resourceType"
                       :formatter="resourceTypeFormatter" width="100" v-if="columns[1].visible"></el-table-column>
      <el-table-column label="权限标识" align="left" header-align="center" prop="permission" v-if="columns[2].visible"/>
      <el-table-column label="显示状态" align="left" header-align="center" prop="hidden" width="80"
                       v-if="columns[3].visible">
        <template #default="scope">
          <el-tag :type="scope.row.hidden === true ? 'danger' : ''" disable-transitions>
            {{ scope.row.hidden === true ? '隐藏' : '显示' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="资源状态" align="left" header-align="center" prop="status" width="80"
                       v-if="columns[4].visible">
        <template #default="scope">
          <el-tag :type="scope.row.status === true ? '' : 'danger'" disable-transitions>
            {{ scope.row.status === true ? '正常' : '停用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="left" header-align="center" width="160" prop="createTime"
                       v-if="columns[5].visible" :show-overflow-tooltip="true">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="240" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" v-if="scope.row.resourceType !== 1"
                     @click="handleUpdate(scope.row)">修改</el-button>
          <el-button link type="primary" icon="Plus" v-if="scope.row.resourceType !== 4"
                     @click="handleAdd(scope.row)">新增</el-button>
          <el-button link type="primary" icon="Delete" v-if="scope.row.resourceType !== 1"
                     @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNumber" v-model:limit="queryParams.pageSize" @pagination="getList"/>
    <!-- 添加或修改菜单对话框 -->
    <el-dialog :title="title" v-model="openDialog" width="680px" append-to-body>
      <el-form :model="form" :rules="rules" ref="appPageRef" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="资源名称" prop="title">
              <el-input v-model="form.title" placeholder="请输入资源名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="permission">
              <el-input v-model="form.permission" placeholder="请输入权限标识" :disabled="form.resourceType === 1" />
              <template #label>
                        <span>
                           <el-tooltip content="控制器中定义的权限字符，如：@PreAuthorize(`@ss.hasPermi('system:user:list')`)"
                                       placement="top">
                              <el-icon><question-filled/></el-icon>
                           </el-tooltip>
                           权限字符
                        </span>
              </template>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.resourceType !== 1">
            <el-form-item prop="facadeIds" label="关联API">
              <el-select v-model="form.facadeIds" multiple placeholder="选择API" style="width: 100%" filterable :popper-options="{ modifiers: [{ name: 'computeStyles', options: { adaptive: false } }] }">
                <el-option v-for="item in appPageFacadeList" :key="item.id" :label="item.title" :value="item.id">
                  <span style="float: left">{{ item.title }} {{ item.requestUrl }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.resourceType === 2">
            <el-form-item prop="appPageWidgets" label="包含组件">
              <el-select v-model="form.appPageWidgets" multiple placeholder="选择组件" style="width: 100%" filterable>
                <el-option v-for="item in appPageWidgetList" :key="item.id" :label="item.title" :value="item.id">
                  <span style="float: left">{{ item.title }} {{ item.requestUrl }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.resourceType !== 3">
            <el-form-item prop="iFrame">
              <template #label>
                        <span>
                           <el-tooltip content="选择是外链则路由地址需要以`http(s)://`开头" placement="top">
                              <el-icon><question-filled/></el-icon>
                           </el-tooltip>是否外链
                        </span>
              </template>
              <el-radio-group v-model="form.outside">
                <el-radio :label="true">是</el-radio>
                <el-radio :label="false">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="form.outside === true">
            <el-form-item label="路由地址" prop="url">
              <el-input v-model="form.url" placeholder="请输入路由地址"/>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.resourceType !== 3">
            <el-form-item prop="hidden">
              <template #label>
                        <span>
                           <el-tooltip content="选择隐藏则路由将不会出现在侧边栏，但仍然可以访问" placement="top">
                              <el-icon><question-filled/></el-icon>
                           </el-tooltip>
                           显示状态
                        </span>
              </template>
              <el-radio-group v-model="form.hidden">
                <el-radio :label="false">是</el-radio>
                <el-radio :label="true">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.resourceType !== 3">
            <el-form-item prop="status">
              <template #label>
                        <span>
                           <el-tooltip content="选择停用则路由将不会出现在侧边栏，也不能被访问" placement="top">
                              <el-icon><question-filled/></el-icon>
                           </el-tooltip>
                           资源状态
                        </span>
              </template>
              <el-radio-group v-model="form.status">
                <el-radio :label="true">是</el-radio>
                <el-radio :label="false">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script setup name="Resource">
import {
  delResource,
  getResource,
  listResource, saveApp,
  saveAppPage, saveAppPageElement
} from "../../../api/ac/ac"
import {getCurrentInstance, reactive, toRefs} from "vue"
import {useRouter} from "vue-router"

const router = useRouter()
const {proxy} = getCurrentInstance()
const resourceList = ref([])
const appPageFacadeList = ref([])
const appPageWidgetList = ref([])
const openDialog = ref(false)
const loading = ref(false)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
let selectCurrRow = ref({})
const loadNodeMap = new Map()
const sys_normal_disable = ref([
  {value: 0, label: '停用'},
  {value: 1, label: '正常'}
]);
// 列显隐信息
const columns = ref([
  {key: 0, label: '资源名称', visible: true},
  {key: 1, label: '权限类型', visible: true},
  {key: 2, label: '权限标识', visible: true},
  {key: 3, label: '显示状态', visible: true},
  {key: 4, label: '资源状态', visible: true},
  {key: 5, label: '创建时间', visible: true},
]);

const data = reactive({
  form: {},
  queryParams: {
    pageNumber: 1,
    pageSize: 10,
    isPage: false,
    code: undefined,
    title: undefined,
    appId: undefined,
    resourceType: 1,
    appPageId: undefined
  },
  rules: {
    title: [{required: true, message: "菜单名称不能为空", trigger: "blur"}],
    permission: [{required: true, message: "权限标识不能为空", trigger: "blur"}],
  }
})

const {queryParams, form, rules} = toRefs(data)

function resourceTypeFormatter(row) {
  switch (row.resourceType) {
    case 1:
      return '应用';
    case 2:
      return '页面';
    case 3:
      return '控件';
    case 4:
      return '元素';
    default:
      return row.resourceType;
  }
}

function toTreeList(resourceList) {
  resourceList.forEach(resource => {
    resource.hasChildren = resource.resourceType !== 4;
  })
  return resourceList
}

/** 查询资源列表 */
function getList() {
  loading.value = true;
  const params = queryParams.value
  listResource(params).then(res => {
    loading.value = false;
    resourceList.value = toTreeList(res.ds.content)
  })
}
/** 查询应用API */
function getAppPageFacadeList() {
  const params = {
    isPage: false,
    resourceType: 5
  }
  listResource(params).then(res => {
    appPageFacadeList.value = res.ds.content
  })
}
function getAppPageWidgetList() {
  const params = {
    isPage: false,
    resourceType: 3
  }
  listResource(params).then(res => {
    appPageFacadeList.value = res.ds.content
  })
}
/** 展开资源 */
function treeTableExpandChange(row, expanded) {
  if (expanded) {
  }
}

// 懒加载
function loadNextNode(row, treeNode, resolve) {
  const id = row.id;
  // 将当前操作保存起来
  loadNodeMap.set(id, row)
  const params = {
    isPage: false
  }
  if (row.resourceType === 1) {
    params.resourceType = 2
    params.appId = row.id
  } else if (row.resourceType === 2) {
    params.resourceType = 4
    params.appPageId = row.id
  }
  listResource(params).then(res => {
    resolve(toTreeList(res.ds.content))
  })
}

/**
 * 在新增类型后根据selectCurrRow的id 获取loadNodeMap 中对应的
 * resolve 进行子节点刷新操作
 * 刷新table 列表
 *
 */
function _reRenderChildrenNodeAfterAdd(resourceId,resourceType) {
  if (loadNodeMap.has(resourceId)) {
    const params = {
      isPage: false
    }
    if(resourceType === 2) {
      params.resourceType = 2
      params.appId = resourceId
    }else if(resourceType === 4) {
      params.resourceType = 4
      params.appPageId = resourceId
    }
    listResource(params).then(res => {
      proxy.$refs.tableDom.store.states.lazyTreeNodeMap.value[resourceId] = toTreeList(res.ds.content)
      proxy.$refs.tableDom.store.states.treeData.value[resourceId].loaded = true
    })
  }
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNumber = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 删除按钮操作 */
function handleDelete(row) {
  proxy.$modal.confirm('是否确认删除页面"' + row.title + '"的数据项？').then(function() {
    return delResource(row.id);
  }).then(function() {
    if(row.resourceType === 2) {
      _reRenderChildrenNodeAfterAdd(row.appId, row.resourceType)
    }else if(row.resourceType === 4) {
      _reRenderChildrenNodeAfterAdd(row.appPageId, row.resourceType)
    }
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {})
}

/** 重置操作表单 */
function reset() {
  form.value = {
    title: undefined,
    appId: undefined,
    outside: false,
    hidden: false,
    status: true
  }
  proxy.resetForm("appPageRef")
}

/** 取消按钮 */
function cancel() {
  openDialog.value = false
  reset()
}

/** 新增按钮操作 */
function handleAdd(row) {
  reset()
  selectCurrRow = row
  if (row.resourceType === 1) {
    form.value.resourceType = 2
    form.value.appId = row.id
    title.value = "添加页面"
  } else if (row.resourceType === 2) {
    form.value.resourceType = 4
    form.value.appPageId = row.id
    title.value = "添加元素"
  }
  openDialog.value = true
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  selectCurrRow = row
  const appPageId = row.id
  const resourceType = row.resourceType
  getResource(appPageId).then(response => {
    form.value = response.ds
    openDialog.value = true
    if (resourceType === 1) {
      title.value = "修改应用"
    } else if (resourceType === 2) {
      title.value = "修改页面"
    } else if (resourceType === 4) {
      title.value = "修改元素"
    }
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["appPageRef"].validate(valid => {
    if (valid) {
      console.log(form.value)
      if (form.value.resourceType === 1) {
        saveApp(form.value).then(res => {
          if (form.value.id !== undefined) {
            proxy.$modal.msgSuccess("修改应用成功");
          } else {
            proxy.$modal.msgSuccess("新增应用成功");
          }
          openDialog.value = false;
          getList()
        })
      } else if (form.value.resourceType === 2) {
        saveAppPage(form.value).then(res => {
          if (form.value.id !== undefined) {
            proxy.$modal.msgSuccess("修改页面成功");
            _reRenderChildrenNodeAfterAdd(selectCurrRow.appId,2)
          } else {
            proxy.$modal.msgSuccess("新增页面成功");
            _reRenderChildrenNodeAfterAdd(selectCurrRow.id,2)
          }
          openDialog.value = false;
        })
      } else if (form.value.resourceType === 4) {
        saveAppPageElement(form.value).then(res => {
          if (form.value.id !== undefined) {
            proxy.$modal.msgSuccess("修改元素成功");
            _reRenderChildrenNodeAfterAdd(selectCurrRow.appPageId,4)
          } else {
            proxy.$modal.msgSuccess("新增元素成功");
            _reRenderChildrenNodeAfterAdd(selectCurrRow.id,4)
          }
          openDialog.value = false;
        })
      }
    }
  })
}
getList();
getAppPageFacadeList();
</script>
